/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

var trow;
var tcol;
var tplayerName;
var players = 1;
var thisPlayer = 0;

$(document).ready(function() {
    init();
    var phase = 1;
    var obj = document.getElementById("numOfPlayers");
    var pObj = document.getElementById("playersList");
    $("#pleaseWait").dialog({autoOpen: false});
    if (obj != null) {
        $(".next").click(function() {
            if (phase == 1) {
                $("#welcome").fadeOut(1000);
                $("#numOfPlayers").delay(1000).fadeIn(1000);
                $("#swap").toggle();
                phase++;
            } else if (phase == 2) {
                $("#swap").hide();
                callAjax("setNumPlayers");
            }
        })
        $("#swap").click(function() {
            if ($("#numOfPlayers").css("display") == "none") {
                $("#uploadForm").fadeOut(1000);
                $("#numOfPlayers").delay(1000).fadeIn(1000);
                $("#swap > span").html("Use XML");
            } else {
                $("#numOfPlayers").fadeOut(1000);
                $("#uploadForm").delay(1000).fadeIn(1000);
                $("#swap > span").html("Back");
            }
        });
    } else if (pObj == null) {
        $(".next").click(function() {
            $("#welcome").fadeOut(1000);
            thisPlayer++;
            $("#playerTitle").html("Set up player number: " + thisPlayer);
            showAddPlayer();
            clearBoard();
            $("#next").unbind('click');
            $("#next").click(function() {
                callAjax("addPlayer");
            });
        });
    } else {
        if ($("#welcome").css("display") == "none") {
            $("#playersList").delay(1000).fadeIn(1000);
        } else {
            $(".next").click(function() {
                $("#welcome").fadeOut(1000);
                $("#playersList").delay(1000).fadeIn(1000);
            });
        }
        $(".playerPick").click(function() {
            tplayerName = $(this).attr("data-name");
            callAjax("pickPlayer");
        });
        $("#playersList > .playerPick").hover(function() {
            $(this).addClass("hoveredPlayer");
        }, function () {
            $(this).removeClass("hoveredPlayer");
        })
    }
});

function init() {
    $(".next").delay(1000).fadeIn(1500);
    $("#addShip").dialog({
        autoOpen: false,
        modal: true,
        buttons: {
            "Add ship": function() {
                callAjax("addShip");
                $( this ).dialog( "close" );
            },
            "Cancel": function() {
                $( this ).dialog( "close" );
            }
        },
        close: function() {

        }
    });
    $("#removeShip").dialog({
        autoOpen: false,
        modal: true,
        draggable:false,
        resizeable: false,
        buttons: {
            "Cancel": function () {
                $(this).dialog("close");
            },
            "Confirm": function () {
                callAjax("removeShip");
                $(this).dialog("close");
            }
        }
    });

}

$(function() {
    $( "#slider-range" ).slider({
        range: true,
        min: 1,
        max: 6,
        values: [1,2],
        step: true,
        slide: function (event, ui) {
            $("#computer").val("" + (ui.values[1] - ui.values[0] + ""));
            $("#human").val("" + ui.values[0] + "");
        }
    })
});

function changePlayerType(type, obj) {
    if (type == "Human") {
        document.getElementById("humanIcon").src = "images/userSelected.png";
        $("#playerType").val("Human");
    } else if (type == "Computer") {
        document.getElementById("humanIcon").src = "images/userUnselected.png";
        $("#playerType").val("Computer");
    }
}

function generateURL(call) {
    
}

function addPlayer() {
    
}

function removePlayer() {
    
}

function callAjax(call) {
    
    var url = getURL(call);
    var req = generateData(call);
    
    $.ajax({
        data: req,
        url: url,
        timeout: 10000000,
        beforeSend: function() {
            showLoading();
        },
        success: function(data) {
            hideLoading();
            processAction(data, call);
            return true;
        },
        error: function(jq, err) {
            hideLoading();
            var msg;
            if (err == "timeout") {
                msg = "Timeout reached while waiting for page";
            } else if (err == "error") {
                msg = "General error while waiting for page";
            } else if (err == "abort") {
                msg = "Page aborted";
            } else {
                msg = "Unknown error, Please try again later";
            }
            showAlert(msg);
            return false;
        }
    });
    return false;
}

function hideLoading() {
    $("#loading").hide();
}

function showLoading() {
    $("#loading").show();
}

function getURL(call) {
    return "WebUi";
}

function generateData(call) {
    if (call == "addPlayer") {
        var name = document.getElementById("playerName").value;
        tplayerName = name;
        var type = document.getElementById("playerType").value;
        var ret = new Object();
        ret.actionName = "addPlayer";
        ret.playerName = name;
        ret.playerType = type;
        return ret;
    }
    if (call == "addShip") {
        var ret = new Object();
        ret.actionName = "addShip";
        ret.col = tcol;
        ret.row = trow;
        ret.dir = $("[name=orientation]").val();
        ret.size = $("[name=shipSize]").val();
        ret.playerName = tplayerName;
        
        return ret;
    }
    if (call == "removeShip") {
        var ret = new Object();
        ret.actionName = call;
        ret.col = tcol;
        ret.row = trow;
        ret.playerName = tplayerName;
        
        return ret;
    }
    if (call == "saveBoard") {
        var ret = new Object();
        ret.actionName = call;
        ret.playerName = tplayerName;
        
        return ret;
    }
    if (call == "setNumPlayers") {
        var ret = new Object();
        ret.actionName = call;
        ret.humanNum = $("#human").val();
        ret.computerNum = $("#computer").val();
        ret.numPlayers = players;
        
        return ret;
    }
    if (call == "getSubStatus") {
        var ret = new Object();
        ret.actionName = call;
        ret.playerName = tplayerName;
        return ret;
    }
    if (call == "isPlayersReady") {
        var ret = new Object();
        ret.actionName = call;
        return ret;
    }
    if (call == "pickPlayer") {
        var ret = new Object();
        ret.actionName = call;
        ret.playerName = tplayerName;
        return ret;
    }
    return "";
}

function clearBoard() {
    $('div[data-col][data-row]').removeClass();
    $('div[data-col][data-row]').addClass("square");
}

function processAction(data, call) {
    var ret = jQuery.parseJSON(data);
    if (ret.r === "ERROR") {
        showAlert(ret.e);
    } else if (ret.r === "OK") {
        if (call == "uploadxml") {
            window.location.href = "WebUi?creator=yes";
            return;
        }
        if (ret.n == "getBoard") {
            showBoard();
            setBoard(null);
            callAjax("getSubStatus");
            $("#next").unbind('click');
            $("#next").click(function() {
                callAjax("saveBoard");
            })
        } else if (ret.n == "nextShip") {
            setBoard(ret.i);
            callAjax("getSubStatus");
        } else if (ret.n == "nextPlayer") {
            thisPlayer++;
            $("#playerTitle").html("Set up player number: " + thisPlayer);
            showAddPlayer();
            clearBoard();
            $("#next").unbind('click');
            $("#next").click(function() {
                callAjax("addPlayer");
            });
        } else if (ret.n == "startGame") {
            window.location.href = "game.jsp";
        } else if (ret.n == "setSubStatus") {
            setAvailableShips(ret.i);
        } else if (ret.n == "Wait") {
            showWait();
            setTimeout('callAjax(\'isPlayersReady\')', 3000);
        }
    } else {
        showAlert("Invalid return info");
    }
        
}

function showWait() {
    if (!($("#pleaseWait").dialog("isOpen"))) {
        $("#pleaseWait").dialog({
           modal: true 
        });
        $("#pleaseWait").dialog("open");
        $("#waitBar").progressbar({
            value: 100
        });
    }
}

function hideBoard() {
    $("#board").fadeOut(1000);
    $("#addPlayer").delay(1500).fadeIn(1000);
    $("#mainBody").animate({
        width: "-=200",
        height: "-=200"
    }, 1000);
    
    emptyBoard();
}

function clearAddPlayer() {
    changePlayerType("Human");
    $("#playerName").val("");
}

function showAddPlayer() {
    clearAddPlayer();
    $("div#mainBody > div").fadeOut(1000);
    $("#addPlayer").delay(1000).fadeIn(1000);
    $("#mainBody").animate({
        width: "480px",
        height: "320px"
    }, 1000);
}

function showBoard() {
    $("#mainBody > div:visible").fadeOut(1000).hide();
    $("#board").delay(1500).fadeIn(1000);
    $("#mainBody").animate({
        width: "600px",
        height: "480px"
    }, 1000);
}

function setAvailableShips(data) {
    var i, j;
    if (data != null) {
        $("#shipSize").html("");
        for (j = 0; j < data.length; j++) {
            for (i = 0; i < data[j].length; i++) {
                if (data[j][i] != "") {
                    $("#shipSize").append("<option value=\"" + data[j][i] + "\">" + data[j][i].replace(/_/," ") + " (" + (j + 1) + ")</option>");
                }
            }
        }
    }
}

function setBoard(data) {
    var i,j;
    if (data != null) {
        for (j = 0; j < data.length; j++) {
            for (i = 0; i < data[j].length; i++) {
                $('div[data-col="' + i + '"][data-row="' + j + '"]').removeClass();
                $('div[data-col="' + i + '"][data-row="' + j + '"]').addClass("square");
                if (data[j][i].sign == "-") {
                    $('div[data-col="' + i + '"][data-row="' + j + '"]').addClass("emptySquare");
                } else if (data[j][i].sign == "X") {
                    $('div[data-col="' + i + '"][data-row="' + j + '"]').addClass("hitSquare");
                } else if (data[j][i].sign == "@") {
                    $('div[data-col="' + i + '"][data-row="' + j + '"]').addClass("markedSquare");
                } else if (data[j][i].sign == "O") {
                    $('div[data-col="' + i + '"][data-row="' + j + '"]').addClass("missedSquare");
                } else if (data[j][i].sign == "#") {
                    $('div[data-col="' + i + '"][data-row="' + j + '"]').addClass("subSquare");
                } else {
                    showAlert("Invalid input from server");
                    return;
                }
            }
        }
    }
    $("[data-col][data-row]").unbind("click");
    $("[data-col][data-row]").click(function() {
        tcol = $(this).attr("data-col");
        trow = $(this).attr("data-row");


        $("#addShip").dialog("open");
     
    });
    $(".subSquare").unbind('click');
    $(".subSquare").click(function () {
        tcol = $(this).attr("data-col");
        trow = $(this).attr("data-row");

        $("#removeShip").dialog("open");
    });
}

function showAlert(msg) {
    $("#errorMsg").dialog("destroy");
    $("#errorMsg").html(msg);
    $("#errorMsg").dialog({
        modal: true,
        draggable:false,
        resizeable: false,
        buttons: {
            "Ok": function () {
                $(this).dialog("close");
            }
        }
    });
}

function ajaxFileUpload() {
    //starting setting some animation when the ajax starts and completes
    $("#loading").ajaxStart(function(){
        showLoading();
    }).ajaxComplete(function(){
        hideLoading();
    });
        
        /*
            prepareing ajax file upload
            url: the url of script file handling the uploaded files
                        fileElementId: the file type of input element id and it will be the index of  $_FILES Array()
            dataType: it support json, xml
            secureuri:use secure protocol
            success: call back function when the ajax complete
            error: callback function when the ajax failed
            
                */
        $.ajaxFileUpload ({
            url:'WebUi?actionName=uploadxml', 
            secureuri:false,
            fileElementId:'xmlfile',
            dataType: 'json',
            success: function (data) {
                if (data.r === "ERROR") {
                    showAlert(data.e);
                } else {
                    hideLoading();
                    if (data.r == "OK") {
                        window.location.href = "index2.jsp?creator=yes";
                    } else {
                        showAlert(data.e);
                    }
                }
            },
            error: function (data, status, e) {
                hideLoading();
                showAlert(e);
            }
        })
        return false;
    } 